<?php
/**
 * Powered By ThinkPHP 5.0.12
 * Copyright (c) 2017 http://www.bojuwang.net All rights reserved.
 * Created by PhpStorm.
 * Date: 2018/4/23 0023
 * Time: 下午 3:22
 * Author: NanTao <260053530@qq.com>
 */
namespace app\index\controller;
use think\Db;
use think\Request;
  class User extends Common
{
    public $userId;
    public function _initialize()
    {
        parent::_initialize();
        $this->uid = session('userId');
    }
    /*
     * 个人中心
     * */
    public function index()
    {
        $user = Db::name('user')->field('avatar,user_nickname,is_true_name,is_partner')->where('id',$this->uid)->find();
        $this->assign('user',$user);
        $msgcount = Db::name('sys_message')->where(['user_id'=>$this->uid,'is_read'=>0])->count();
        $this->assign('msgcount',$msgcount);
        return $this->fetch();
    }
    /*
     * 修改个人资料
     * */
    public function show()
    {
        if (request()->isPost())
        {
            $data = input('param.');
            $res = Db::name('user')->where('id',$this->uid)->update($data);
            if ($res > 0 || $res == 0) {
                exit(json_encode(['code'=>0,'msg'=>'修改成功'],320));
            } else {
                exit(json_encode(['code'=>1,'msg'=>'系统错误,修改失败'],320));
            }
        } else {
            $info = Db::name('user')->where('id',$this->uid)->find();
            $this->assign('info',$info);
            return $this->fetch();
        }
    }
    /*
     * 修改头像
     * */
    public function saveAvatar()
    {
        $base = input('param.base');
        $arr = $this->uploadBase($base);
        if ($arr['code'] == 0) {
            $res = Db::name('user')->where('id',$this->uid)->setField('avatar',$arr['path']);
            if ($res > 0 || $res == 0)
            {
                json_msg(0,'头像修改成功');
            } else {
                json_msg(1,'系统错误,修改头像失败');
            }
        } else {
            json_msg(1,$arr['msg']);
        }
    }
    /*
     * 消息列表
     * */
    public function msg()
    {
        $list = Db::name('sys_message')->where('user_id',$this->uid)->select();
        $this->assign('list',$list);
        return $this->fetch();
    }
    /*
     * 消息详情
     * */
    public function msgshow()
    {
        $id = input('param.id');
        $info = Db::name('sys_message')->where('id',$id)->find();
        Db::name('sys_message')->where('id',$id)->setField('is_read',1);
        $this->assign('info',$info);
        return $this->fetch();
    }
    /*
      * 收货地址
      * */
    public function address()
    {
        $list = Db::name('user_address')->where('user_id',$this->uid)->order('is_default desc,id desc')->select();
        foreach ($list as $k=>$v)
        {
            $list[$k]['province'] = province($v['province_code']);
            $list[$k]['city'] = city($v['city_code']);
            $list[$k]['area'] = area($v['area_code']);
        }
        $this->assign('list',$list);
        return $this->fetch();
    }
    /*
     * 添加收获地址
     * */
    public function saveAddress()
    {
        $action = input('param.action');
        $addressId = input('param.addressId');
        if (request()->isPost())
        {
            $name = input('param.name');
            $mobile = input('param.mobile');
            $province = input('param.province');
            $city = input('param.city');
            $area = input('param.area');
            $info = input('param.info');
            $userId = session('userId');
            $isDefault = input('param.isDefault');
            Db::name('user_address')->where('user_id',$userId)->setField('is_default',0);
            if (isset($isDefault))
            {
                $data = ['is_default'=>$isDefault];
            } else {
                $data = [
                    'name'=>$name,
                    'mobile'=>$mobile,
                    'province_code'=>$province,
                    'city_code'=>$city,
                    'area_code'=>$area,
                    'info'=>$info,
                    'is_default'=>1,
                    'user_id'=>$userId,
                ];
            }
            if (isset($addressId) && !empty($addressId)) {
                if (Db::name('user_address')->where('id',$addressId)->update($data))
                {
                    json_msg(0,'修改成功');
                } else {
                    json_msg(1,'修改失败');
                }
            } else {
                if (Db::name('user_address')->insert($data))
                {
                    json_msg(0,'添加成功');
                } else {
                    json_msg(1,'添加失败');
                }
            }
        } else {
            switch ($action) {
                case 'add':
                    $title = '新增地址';
                    break;
                case 'edit':
                    $title = '修改地址';
                    $info = Db::name('user_address')->where('id',$addressId)->find();
                    $this->assign('info',$info);
                    break;
            }
            $this->assign('title',$title);
            $provinces = Db::name("provinces")->select();
            $this->assign("provinces",$provinces);
            return $this->fetch();
        }
    }
    /*删除收获地址*/
      public function delAddress()
      {
          $addressId = input('param.addressId');
          if (Db::name('user_address')->delete($addressId))
          {
              json_msg(0,'删除成功');
          } else {
              json_msg(1,'删除失败');
          }
      }
    /*
     * 商品收藏
     * */
    public function goodsColl()
    {
        $list = Db::name('goods_collection')->alias('a')
            ->field('b.img_url,b.sell_price,b.title,b.market_price,a.id,a.goods_id')
            ->join('goods b','a.goods_id=b.id')
            ->where('a.user_id',$this->uid)
            ->select();
        $this->assign('list',$list);
        return $this->fetch();
    }
    /*
     * 用户银行卡
     * */
    public function bank()
    {
        $list = Db::name('user_bank')->where('user_id',$this->uid)->select();
        $this->assign('list',$list);
        $trueName = get_user_info_data($this->uid,'true_name');
        $this->assign('trueName',$trueName);
        return $this->fetch();
    }
    /*
     * 添加银行卡
     * */
    public function addBank()
    {
        $data = input('param.');
        $data['user_id'] = $this->uid;
        if (Db::name('user_bank')->insert($data))
        {
            $id = Db::name('user_bank')->getLastInsID();
            json_msg_data(0,'绑定成功',$id);
        } else {
            json_msg(1,'绑定失败');
        }
    }
    /*
     * 删除银行卡
     * */
    public function delBank()
    {
        $bankId = input('param.bankId');
        if (Db::name('user_bank')->delete($bankId))
        {
            json_msg(0,'解绑成功');
        } else {
            json_msg(1,'解绑失败');
        }
    }
    /*
     * 文章标题
     * */
    public function articles()
    {
        $category_id = input('param.category_id');
        $data = get_article_data($category_id);
        $this->assign('data',$data);
        return $this->fetch();
    }
    /*
     * 文章详情
     * */
    public function article()
    {
        $id = input('param.id');
        $category_id = input('param.category_id');
        if (isset($category_id))
        {
            $data = get_article_data($category_id);
            $info = $data['list'][0];
        }
        if (isset($id)) {
            $info = Db::name('article')->find($id);
        }
        $this->assign('info',$info);
        $this->assign('title',$info['title']);
        $this->assign('content', $info['summary']);
        $this->assign('icon', $info['img_url']);
        return $this->fetch();
    }
    /*
     * 实名认证
     * */
    public function certify()
    {
        if (request()->isPost())
        {
            $trueName = input('param.trueName');
            $mobile = input('param.mobile');
            $code = input('param.code');
            $card = input('param.card');
            if (!cookie($mobile))
            {
                json_msg(1,'验证码已过期');
            }
            if ($code != cookie($mobile))
            {
                json_msg(1,'验证码错误');
            }
            $data = [
                'true_name'=>$trueName,
                'mobile'=>$mobile,
                'card'=>$card,
                'is_true_name'=>1
            ];
            $result = Db::name('user')->where('id',$this->uid)->update($data);
            if ($result>0)
            {
                json_msg(0,'认证已提交,等待后台审核');
            } else {
                json_msg(1,'提交失败');
            }
        } else {
            $info = Db::name('user')->field('id,true_name,card,is_true_name,mobile')->where('id',$this->uid)->find();
            $this->assign('info',$info);
            return $this->fetch();
        }
    }
    /*
     * 合伙人申请
     * */
    public function partner()
    {
        if (request()->isPost())
        {
            $partner_name = input('param.partner_name');
            $partner_mobile = input('param.partner_mobile');
            $partner_city = input('param.partner_city');
     
            $data = [
                'partner_name'=>$partner_name,
                'partner_mobile'=>$partner_mobile,
                'partner_city'=>$partner_city,
                'is_partner'=>1
            ];
            $result = Db::name('user')->where('id',$this->uid)->update($data);
            if ($result>0)
            {
                json_msg(0,'认证已提交,等待后台审核');
            } else {
                json_msg(1,'提交失败');
            }
        } else {
            $info = Db::name('user')->field('id,partner_name,partner_mobile,partner_city,is_partner')->where('id',$this->uid)->find();
            $this->assign('info',$info);
            return $this->fetch();
        }
    }
    /*
     * 合伙人业绩统计
     * */
    public function partnerlist()
    {
        $user_list =get_user_agent($this->uid);
        $is_str = '';
        foreach($user_list as $vo){
            $is_str.=$vo['next_user_id'].',';
        }
        $is_str = substr($is_str,0,-1);
        $partnerlist = Db::name('goods_order')->alias('o')
            ->join('user u','u.id = o.user_id')
            ->field('o.pay_time,o.pay_money,u.user_nickname')
            ->where('o.user_id','in',$is_str)
            ->where('o.status','neq',0)
            ->select();
        $this->assign('list',$partnerlist);
        return $this->fetch();
    }
    /*
     * 提现申请
     * */
    public function cash()
    {
        if (request()->isPost())
        {
            $bankId = input('param.bankid');
            $money = input('param.money');
            $mobile = input('param.mobile');
            $code = input('param.code');
            if (!cookie($mobile))
            {
                json_msg(1,'验证码已过期');
            }
            if ($code != cookie($mobile))
            {
                json_msg(1,'验证码错误');
            }
            $bank = Db::name("user_bank")->where('id',$bankId)->find();
            $userBalance = get_user_info_data($this->uid,'balance');
            if ($userBalance < $money)
            {
                json_msg(1,'您的账户可用余额不足');
            }
            $userFrozen = get_user_info_data($this->uid,'frozen');
            $frozen = $userFrozen + $money;
            $balance = $userBalance - $money;
            $result =  Db::name('user')->where('id',$this->uid)->update(['balance'=>$balance,'frozen'=>$frozen]);
            if ($result) {
                $cash_cost = (sysconf('cash_cost')/100) * $money;
                $cash_money = $money - $cash_cost - sysconf('cash_tax');
                $data = [
                    'user_id' => $this->uid,
                    'money' => $money,
                    'user_bank_id' => $bankId,
                    'bank_account' => $bank['account'],
                    'bank_name' => $bank['name'],
                    'bank_bank'=>$bank['bank'],
                    'cash_cost'=>$cash_cost,
                    'cash_money'=>$cash_money,
                    'cash_tax'=>sysconf('cash_tax'),
                ];
                Db::name('user_cash')->insert($data);
                $cashId = Db::name('user_cash')->getLastInsID();
                post_user_balance_log($this->uid,'-',$money,"申请提现{$money}元",1,$cashId);
                json_msg(0,'您的提现申请已提交到后台,请耐心等待!!!');
            } else {
                json_msg(1,'申请失败');
            }
        } else {
            $bank = Db::name('user_bank')->where('user_id',$this->uid)->select();
            $this->assign('bank',$bank);
            return $this->fetch();
        }
    }
    /*
     * 我的代理
     * */
    public function agent()
    {
        $data = get_user_agent($this->uid);
        $this->assign('list',$data);
        return $this->fetch();
    }
    /*
    * 我的账户
    * */
    public function account()
    {
        $balance = Db::name('user_balance')->where('user_id',$this->uid)->order('add_time desc')->select();
        $this->assign('balance',$balance);
        $cash = Db::name('user_cash')->where('user_id',$this->uid)->order('add_time desc')->select();
        $this->assign('cash',$cash);
        $userBalance = get_user_info_data($this->uid,'balance');
        $this->assign('userBalance',$userBalance);
        return $this->fetch();
    }
    /*
     * 我的优惠券
     * */
    public function coupon()
    {
        $list = get_user_coupon($this->uid);
        $this->assign('list',$list);
        $list1 = get_user_coupon($this->uid,0);
        $this->assign('list1',$list1);
        $list2 = get_user_coupon($this->uid,1);
        $this->assign('list2',$list2);
        $list3 = get_user_coupon($this->uid,2);
        $this->assign('list3',$list3);
        return $this->fetch();
    }
    /*
     * 删除优惠券
     * */
    public function delCoupon()
    {
        $id = input('param.id');
        if (Db::name('user_coupon')->delete($id))
        {
            json_msg(0,'已删除');
        } else {
            json_msg(1,'删除失败');
        }
    }
    /*
     * 邀请好友
     * */
    public function please()
    {
        $link = sysconf('website')."/index/index/index/parentId/".$this->uid;
        $this->assign('link',$link);
        $user = get_user_model($this->uid);
        $this->assign('user',$user);
        return $this->fetch();
    }


    /*生成二维码*/
    public function pleaseshow()
    {
        $savepath = 'public/upload/userqcode';//存放在当前目录的upload文件夹下
        $savename = get_user_info_data(session('userId'),'user_name').".jpg";
        $path = $savepath.'/'.$savename;
        $url = sysconf('website')."/index/index/index/parentId/".$this->uid;
        $qrcode = $this->createQrcode($url,$path,'');
        $this->assign('qrcode',$qrcode);
        $user = get_user_model($this->uid);
        $this->assign('user',$user);
        return $this->fetch();
    }
    /*用户反馈*/
    public function feedback()
    {
        if (request()->isPost())
        {
            $content = input('param.content');
            $userId = $this->uid;
            $userName = get_user_info_data($userId,'user_name');
            $addIp = $_SERVER['REMOTE_ADDR'];
            $data = [
                'content'=>$content,
                'user_id'=>$userId,
                'user_name'=>$userName,
                'add_ip'=>$addIp,
                'status'=>1
            ];
            $result=Db::name('feedback')->insert($data);

            if ($result) {
                json_msg('0','感谢您的反馈');
            } else {
                json_msg('1','提交失败');
            }
        } else{
            return $this->fetch();
        }
    }





     public function integral()
    {
        $userId = session('userId');
        $user = get_user_model($userId );
        $this->assign('user',$user);
        $list = Db::name('user_point')->where('user_id',$userId )->order('add_time desc')->select();
        $this->assign('list',$list);

        return $this->fetch();
    }
}